#include "wx/wxprec.h"
#include "wx/stdpaths.h"
#include "wx/utils.h"
#include "wx/filename.h"
#include <unistd.h>

void wxStandardPaths::SetInstallPrefix( const wxString& prefix ) {
  m_prefix = prefix;
}

wxString wxStandardPaths::GetUserConfigDir() const {
  return wxFileName::GetHomeDir();
}

wxString wxStandardPaths::GetExecutablePath() const {
  wxString exeStr;
  char buf[4096];
  int result = readlink( "/proc/self/exe", buf, WXSIZEOF( buf ) - sizeof( char ) );
  if( result != -1 ) {
    buf[result] = '\0';
    if( strcmp( buf, "(deleted)" ) != 0 ) {
      exeStr = wxString( buf, wxConvLibc );
    }
  }
  if( exeStr.empty() ) {
    wxGetEnv( wxT( "   " ), &exeStr );
  }
  if( !exeStr.empty() ) {
    return exeStr;
  }
  return wxStandardPathsBase::GetExecutablePath();
}

void wxStandardPaths::DetectPrefix() {
  wxString exeStr = GetExecutablePath();
  if( !exeStr.empty() ) {
    size_t pos = exeStr.rfind( wxT( "/bin/" ) );
    if( pos != wxString::npos ) {
      m_prefix.assign( exeStr, 0, pos );
    }
  }
  if( m_prefix.empty() ) {
    m_prefix = wxT( "/usr/local" );
  }
}

wxString wxStandardPaths::GetInstallPrefix() const {
  if( m_prefix.empty() ) {
    wxStandardPaths *pathPtr = wx_const_cast( wxStandardPaths *, this );
    pathPtr->DetectPrefix();
  }
  return m_prefix;
}

wxString wxStandardPaths::GetConfigDir() const {
  return _T( "/etc" );
}

wxString wxStandardPaths::GetDataDir() const {
  return AppendAppName( GetInstallPrefix() + _T( "/share" ) );
}

wxString wxStandardPaths::GetLocalDataDir() const {
  return AppendAppName( _T( "/etc" ) );
}

wxString wxStandardPaths::GetUserDataDir() const {
  return AppendAppName( wxFileName::GetHomeDir() + _T( "/." ) );
}

wxString wxStandardPaths::GetPluginsDir() const {
  return AppendAppName( GetInstallPrefix() + _T( "/lib" ) );
}

wxString wxStandardPaths::GetLocalizedResourcesDir( const wxChar *lang, ResourceCat category ) const {
  if( category != ResourceCat_Messages ) {
    return wxStandardPathsBase::GetLocalizedResourcesDir( lang, category );
  }
  return GetInstallPrefix() + _T( "/share/locale/" ) + lang + _T( "/LC_MESSAGES" );
}
